#include "headfiles.h"

using namespace std;

int findString(char **str_array, int str_num, char *str) {
    if (str_array == NULL ||
        str_num <= 0) {
        cout << "Invalid argument, NULL!" << endl;
        return -1;
    }

    // The string to be searched can be a NULL string

    int start = 0;
    int end = str_num;
    int mid_loc;

    if (str == NULL) {
        while (start < end) {
            if (str == str_array[start]) {
                return start;
            }

            start++;
        }

        return -1;
    }

    while (start < end) {
        mid_loc = (start + end) / 2;
        while (str_array[mid_loc] == NULL) {
            ++mid_loc;
            if (mid_loc >= end) {
                break;
            }
        }

        // All strings are NULL after mid point
        // Update end to the middle location
        if (mid_loc >= end) {
            end = (start + end) / 2;
        }
        // Some string is non-NULL, compare to str
        else {
            int ret_code = strcmp(str, str_array[mid_loc]);
            if (ret_code == 0) {
                return mid_loc;
            }
            else if (ret_code < 0) {
                end = mid_loc;
            }
            else {
                start = mid_loc + 1;
            }
        }
    }

    return -1;
}

